package com.service.impl;




import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.entity.Token;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dao.TokenDao;
import com.service.TokenService;
import com.utils.CommonUtil;
import com.utils.PageUtils;
import com.utils.Query;


/**
 * token
 */
@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenDao, Token> implements TokenService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<Token> page = this.selectPage(
                new Query<Token>(params).getPage(),
                new EntityWrapper<Token>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<Token> selectListView(Wrapper<Token> wrapper) {
        return baseMapper.selectListView(wrapper);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params,
                               Wrapper<Token> wrapper) {
        Page<Token> page =new Query<Token>(params).getPage();
        page.setRecords(baseMapper.selectListView(page,wrapper));
        PageUtils pageUtil = new PageUtils(page);
        return pageUtil;
    }

    @Override
    public String generateToken(Integer userId,String username, String tableName, String role) {
        Token tokenEntity = this.selectOne(new EntityWrapper<Token>().eq("userId", userId).eq("role", role));
        String token = CommonUtil.getRandomString(32);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR_OF_DAY, 1);
        if(tokenEntity!=null) {
            tokenEntity.setToken(token);
            tokenEntity.setExpireTime(cal.getTime());
            this.updateById(tokenEntity);
        } else {
            this.insert(new Token(userId,username, tableName, role, token, cal.getTime()));
        }
        return token;
    }

    @Override
    public Token getToken(String token) {
        Token tokenEntity = this.selectOne(new EntityWrapper<Token>().eq("token", token));
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime()<new Date().getTime()) {
            return null;
        }
        return tokenEntity;
    }
}
